package com.xmd.red.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xmd.red.bean.RedPacket;
import com.xmd.red.config.WxConfig;
import com.xmd.red.dao.RedJdbcDao;
import com.xmd.red.dao.RedPacketDao;
import com.xmd.red.ro.RedRo;
import com.xmd.red.utils.AESSecurityUtil;
import com.xmd.red.utils.CommonResult;
import com.xmd.red.utils.RedTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.mongodb.morphia.Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by superbone on 2016/10/31.
 */
@Service
public class RedPacketService {

    private Logger log = LoggerFactory.getLogger("红包");

    @Resource
    private WxConfig wxConfig;
    @Resource
    private RedPacketDao dao;
    @Resource
    private RedJdbcDao jdbcDao;

    public CommonResult send(String params, String clientIp, String serverIp) {

        log.info("send");

        RedRo redRo = null;
        try {
            log.info("申请红包:"+params);
            String jsonStr = AESSecurityUtil.decrypt(params,wxConfig.getAesKey());
            log.info("申请红包:"+jsonStr);
           redRo = JSON.parseObject(jsonStr, RedRo.class);
        } catch (Exception e) {
            log.error("申请红包参数解析错误");
        }
        if(redRo==null){
            return CommonResult.errorParams("参数错误");
        }



        if(RedTimeUtil.isClose()){
            return CommonResult.errorParams("本轮10000个红包已经发完,春节七天有惊喜.");
        }

        if(!RedTimeUtil.isRightTime()){
            return CommonResult.errorParams("红包活动暂时关闭,请您稍后再试.");
        }

        int deviceCount = dao.queryDeviceCount(redRo.getDeviceId());
        int openIdCount = dao.queryOpenIdCount(redRo.getOpenId());
        if(deviceCount>0||openIdCount>0){
            return CommonResult.errorParams("已经申请过红包了");
        }




        RedPacket red = new RedPacket();
        red.setCreateTime(new Date());
        red.setClientIp(clientIp);
        red.setDeviceId(redRo.getDeviceId());
        red.setFeedback(0);
        red.setDeviceType(redRo.getDeviceType());
        red.setLastUpdateTime(new Date());
        red.setOpenId(redRo.getOpenId());
        red.setServerIp(serverIp);
        red.setUserId(redRo.getUserId());
        Double num = dao.getRandom()*0.01;
        DecimalFormat df = new DecimalFormat("######0.00");
        String numStr = df.format(num);
        num = NumberUtils.createDouble(numStr);
        red.setTotal(num);
        red.setState(0);
        dao.save(red);

        JSONObject result = new JSONObject();
        result.put("up",wxConfig.getRedPacketUpStr());
        result.put("down",wxConfig.getRedPacketDownStr());
        result.put("num",num);
        log.info("申请成功!");
        return CommonResult.ok(result);
    }

    public CommonResult confirm(String params) {

        log.info("confirm");

        if(RedTimeUtil.isClose()){
            return CommonResult.errorParams("本轮10000个红包已经发完,春节七天有惊喜.");
        }

        if(!RedTimeUtil.isRightTime()){
            return CommonResult.errorParams("红包活动暂时关闭,请您稍后再试.");
        }

        String deviceId = null;
        try {
            log.info("确认领取红包:"+params);
            String jsonStr = AESSecurityUtil.decrypt(params,wxConfig.getAesKey());
            log.info("确认领取红包:"+jsonStr);
            deviceId = JSON.parseObject(jsonStr).getString("deviceId");
        } catch (Exception e) {
            log.error("确认领取红包参数解析错误");
        }
        if(StringUtils.isEmpty(deviceId)){
            return CommonResult.errorParams("参数错误");
        }
        RedPacket red = dao.queryByDeviceId(deviceId);
        if(red==null){
            return CommonResult.errorParams("错误的设备编号");
        }
        red.setState(1);
        dao.save(red);
        log.info("确认成功!");
        return CommonResult.ok();
    }

    public CommonResult feedback(String params) {

        log.info("feedback");

        if(RedTimeUtil.isClose()){
            return CommonResult.errorParams("本轮10000个红包已经发完,春节七天有惊喜.");
        }

        if(!RedTimeUtil.isRightTime()){
            return CommonResult.errorParams("红包活动暂时关闭,请您稍后再试.");
        }

        String deviceId = null;
        try {
            log.info("未收到红包反馈:"+params);
            String jsonStr = AESSecurityUtil.decrypt(params,wxConfig.getAesKey());
            log.info("未收到红包反馈:"+jsonStr);
            deviceId = JSON.parseObject(jsonStr).getString("deviceId");
        } catch (Exception e) {
            log.error("确认领取红包参数解析错误");
        }
        if(StringUtils.isEmpty(deviceId)){
            return CommonResult.errorParams("参数错误");
        }
        RedPacket red = dao.queryByDeviceId(deviceId);
        if(red==null){
            return CommonResult.errorParams("错误的设备编号");
        }
        red.setFeedback(1);
        dao.save(red);
        log.info("反馈成功!");
        return CommonResult.ok();
    }

    public CommonResult test(String params) {
        String result = null;
        try {
            result = AESSecurityUtil.encrypt(params,wxConfig.getAesKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.ok(result);
    }

    public CommonResult importData(){

        int count = jdbcDao.count();
        int countTime = count/100 +1;
        for(int i=0;i<countTime;i++){
            int start = i*100;
            int num = 100;
            log.info("执行第<"+i+">100次循环");
            List<RedPacket> list = jdbcDao.query(start,num);
            Iterable<Key<RedPacket>> keys = dao.save(list);
            Iterator<Key<RedPacket>> it = keys.iterator();
            while(it.hasNext()){
                Key<RedPacket> next = it.next();
                log.info(next.getId().toString());
            }
        }
        return CommonResult.ok();
    }
}
